package com.jjz.id.common.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jjz.id.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Instant;

/**
 * @author ZJL
 * @create 2025-05-27-15:50
 */

public class CustomMetaObjectHandler implements MetaObjectHandler {
    private static final Logger log = LoggerFactory.getLogger(CustomMetaObjectHandler.class);
    // 插入时填充字段
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.strictInsertFill(metaObject, "createTime", () -> {
            return Instant.now();
        }, Instant.class);
        this.strictInsertFill(metaObject, "createUser", () -> {
            return this.tryGetUserName();
        }, String.class);
        this.strictInsertFill(metaObject, "version", () -> {
            return 1;
        }, Integer.class);
    }
    //更新时填充字段
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictUpdateFill(metaObject, "updateTime", () -> {
            return Instant.now();
        }, Instant.class);
        this.strictUpdateFill(metaObject, "updateUser", () -> {
            return this.tryGetUserName();
        }, String.class);
    }

    private String tryGetUserName() {
        try {
            return SecurityUtils.getCurrentUser();
        } catch (Exception var2) {
            return "guest";
        }
    }
}
